package com.qn;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import com.qn.common.code.ErrorCode;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ErrorCodeScanner {

    private static final String[] PACKAGE_NAMES = {"ErrorCodeConstants", "GlobalErrorCodeConstants"};

    public static Map<Integer, ErrorCode> scanErrorCodes(String packageName) {
        // 根据包名扫描所有枚举类，并获取所有ErrorCode字段
        Set<Class<?>> classes = ClassUtil.scanPackage(packageName, (clazz) -> CollUtil.contains(Arrays.asList(PACKAGE_NAMES), clazz.getSimpleName()));
        Map<Integer, ErrorCode> errorCodeMap = new HashMap<>();
        for (Class<?> clazz : classes) {
            Field[] fields = ReflectUtil.getFields(clazz);
            for (Field field : fields) {
                // 判断字段类型是否为ErrorCode
                if (field.getType() == ErrorCode.class) {
                    ErrorCode errorCode = (ErrorCode) ReflectUtil.getFieldValue(clazz, field);
                    errorCodeMap.put(errorCode.getCode(), errorCode);
                }
            }
        }

        return errorCodeMap;
    }

    public static void main(String[] args) {
        Map<Integer, ErrorCode> errorCodes = scanErrorCodes("com.qn");
        for (Map.Entry<Integer, ErrorCode> entry : errorCodes.entrySet()) {
            System.out.println("Code: " + entry.getKey() + ", Description: " + entry.getValue());
        }
    }
}
